package com.example.fish.service.impl;

import com.example.fish.mapper.BlogMapper;
import com.example.fish.mapper.LikeInfoMapper;
import com.example.fish.pojo.Blog;
import com.example.fish.pojo.LikeDetail;
import com.example.fish.pojo.LikeInfo;
import com.example.fish.pojo.LikeInfoExample;
import com.example.fish.service.LikeInfoService;
import com.example.fish.service.ex.LikeInfoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LikeInfoServiceImpl implements LikeInfoService {

    @Autowired
    private LikeInfoMapper likeInfoMapper;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public Boolean isLiked(Integer userid, Integer blogid) {
        LikeInfoExample example = new LikeInfoExample();
        example.createCriteria().andUseridEqualTo(userid).andPostidEqualTo(blogid);
        int i = likeInfoMapper.countByExample(example);
        if (i == 0){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void save(Integer blogid, Integer userid) {
        LikeInfo likeInfo = new LikeInfo();
        likeInfo.setPostid(blogid);
        likeInfo.setUserid(userid);
        // 创建 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss");
        // 获取当前时间
        Date date = new Date();
        // 格式化日期，并输出结果
        String formattedDate = sdf.format(date);
        likeInfo.setLiketime(formattedDate);
        int insert = likeInfoMapper.insert(likeInfo);
        if (insert != 1){
            throw new LikeInfoException("点赞发生错误");
        }
    }

    @Override
    public void delete(Integer blogid, Integer userid) {
        LikeInfoExample likeInfoExample = new LikeInfoExample();
        likeInfoExample.createCriteria().andPostidEqualTo(blogid).andUseridEqualTo(userid);
        int i = likeInfoMapper.deleteByExample(likeInfoExample);
        if (i  != 1){
            throw new LikeInfoException("取消点赞发生错误");
        }
    }

    @Override
    public List<LikeDetail> findByUserid(Integer userid) {
        LikeInfoExample example = new LikeInfoExample();
        example.createCriteria().andUseridEqualTo(userid);
        List<LikeDetail> list = new ArrayList<>();
        List<LikeInfo> likeInfos = likeInfoMapper.selectByExample(example);
        for (LikeInfo likeInfo : likeInfos) {
            Blog blog = blogMapper.selectByPrimaryKey(likeInfo.getPostid());
            LikeDetail likeDetail = new LikeDetail();
            likeDetail.setBlogid(blog.getPostid());
            likeDetail.setTime(likeInfo.getLiketime());
            likeDetail.setContent(blog.getContent());
            likeDetail.setTitle(blog.getTitle());
            list.add(likeDetail);
        }
        return list;
    }
}
